package org.nood.iptv.utils;

import android.content.Context;
import android.net.TrafficStats;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

/**
 *
 * @author Noodlewar
 * @date 2017/5/21
 */
public class Utils {

    private static StringBuilder formatBuilder;
    private static Formatter formatter;
    private static long lastTotalRxBytes = 0;
    private static long lastTimeStamp = 0;

    static {
        formatBuilder = new StringBuilder();
        formatter = new Formatter(formatBuilder, Locale.getDefault());
    }

    /**
     * 把毫秒转换成 1:20:30形式
     */
    public static String stringForTime(int time) {
        int totalSeconds = time / 1000;
        int seconds = totalSeconds % 60;

        int minutes = (totalSeconds / 60) % 60;

        int hours = totalSeconds / 3600;

        formatBuilder.setLength(0);
        if (hours > 0) {
            return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return formatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    /**
     * 判断是否为网络资源
     *
     * @param uri
     * @return
     */
    public static boolean isNetUri(String uri) {
        boolean result = false;
        if (uri != null) {
            if (uri.toLowerCase().startsWith("http") || uri.toLowerCase().startsWith("rtsp") || uri.toLowerCase().startsWith("mms")) {
                result = true;
            }
        }
        return result;
    }

    /**
     * 获取当前网速
     *
     * @param context 上下文
     * @return 当前网速
     */
    public static String getNetSpeed(Context context) {
        String netSpeed = "0 kb/s";

        // 转为kB
        long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);
        long nowTimeStamp = System.currentTimeMillis();
        // 毫秒转换
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        netSpeed = String.valueOf(speed) + "kb/s";
        return netSpeed;
    }

    /**
     * 获取系统时间
     */
    public static String getSystemTime() {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        return format.format(new Date());
    }

}
